package com.wb.proxy.javassist;

import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

import java.lang.reflect.Method;

/**
 * @author 魏彪
 */
public class TargetProxy implements MethodHandler {

    public Object getProxy(Class<?> clazz) throws InstantiationException, IllegalAccessException {
        //代理工厂
        ProxyFactory proxyFactory = new ProxyFactory();

        // 设置需要创建子类的父类
        proxyFactory.setSuperclass(clazz);

        // 在调用目标方法时，javassist会回调MethodHandler接口方法进行拦截
        // 来实现你自己的代理逻辑，类似于JDK中的InvocationHandler接口
        Object proxy = proxyFactory.createClass().newInstance();
        ((ProxyObject) proxy).setHandler(this);
        // 通过字节码技术动态创建子类实例
        return proxy;
    }

    @Override
    public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
        System.out.println("要调用的方法名：" + thisMethod.getName());
        System.out.println(proceed.getName());
        System.out.println("开启事务......");
        Object ret = proceed.invoke(self, args);
        System.out.println("提交事物");
        return ret;
    }
}
